<template>
  <view class="con-oil-price-wraper">
    <view class="info">
      <uni-forms ref="baseForm" :rules="formRules" :modelValue="oilPriceForm" label-position="top" label-width="120">
        <view class="title_line">调整油价</view>
        <uni-forms-item label="选择油站" name="stationId">
          <uni-data-select v-model="oilPriceForm.stationId" :localdata="stationList" @change="stationChange"></uni-data-select>
        </uni-forms-item>
        <uni-table ref="table" border emptyText="暂无更多数据">
          <uni-tr>
            <uni-th width="150" align="center">油品</uni-th>
            <uni-th width="150" align="center">油站价(元/L)</uni-th>
          </uni-tr>
          <uni-tr v-for="(item, index) in oilPriceForm.stationOillGunPriceList" :key="index">
            <uni-td align="center">{{ item.oilName }}</uni-td>
            <uni-td align="center">
              <view @click="showInput(index, item)">
                <text v-if="!item.isEdit" style="color: #f8c58c; font-size: 18px; margin-right: 5px">{{ item.oilStationPrice ? item.oilStationPrice : 0 }}</text>
                <uni-easyinput v-else focus v-model="item.oilStationPrice" @confirm="priceConfirm(index, item)" @blur="priceConfirm(index, item)" :maxlength="11" :trim="true"></uni-easyinput>
                <!-- <view style="display: inline-block;float: right;">
									<uni-icons type="compose" size="12"></uni-icons>
									<text style="font-size: 12px;">
										点击修改
									</text>
								</view> -->
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="title_line" style="margin-top: 30rpx">其他设置</view>
        <uni-forms-item label="生效日期" name="effectDate">
          <radio-group @change="handleChangeRadia">
            <label class="radio" v-for="(item, index) in radioList" :key="item.name">
              <radio :value="item.value" style="transform: scale(0.7)" :checked="item.value === '1'" color="#2979ff" />
              <text style="color: #666">{{ item.name }} </text>
            </label>
          </radio-group>
          <!-- 立即生效 -->
          <view v-if="!effectdateInfo.isYuYue">
            <uni-datetime-picker v-model="oilPriceForm.effectDate" type="datetime" return-type="string" disabled />
          </view>
          <!-- 预约生效 时间选择 -->
          <view style="display: flex; align-items: center; margin-top: 30rpx">
            <uni-datetime-picker v-if="effectdateInfo.isYuYue" v-model="effectdateInfo.effect_date" type="date" return-type="string" @change="changeDate" style="width: 60%" />
            <uni-data-select v-if="effectdateInfo.isYuYue" v-model="effectdateInfo.effect_time" :localdata="timeList" @change="changeTime" style="width: 40%" />
          </view>
        </uni-forms-item>
        <uni-forms-item label="调价消息推送时间">
          <uni-data-checkbox multiple :localdata="hobbys" v-model="pushDateCheckboxVal" @change="hanleImmediatelyPushDate" />
          <uni-datetime-picker v-model="oilPriceForm.pushDate" type="datetime" return-type="string" />
        </uni-forms-item>
      </uni-forms>
    </view>
    <view class="operate">
      <view class="operate-container">
        <view style="margin-bottom: 20rpx; width: 100%">
          <u-button :disabled="isDisabled" text="确认" color="#F59B1E" @click="updateOilGunPrice"></u-button>
        </view>
        <u-button color="#FFF" @click="goBack"><text style="color: black">取消</text></u-button>
      </view>
    </view>
  </view>
</template>

<script>
import { getStationInfo, getListByEnterpriseOrStationId, smallProgramUpdateOilGunPrice } from "@/common/yftx-api.js";
export default {
  data() {
    return {
      radioList: [
        {
          name: "立即生效",
          value: "1",
        },
        {
          name: "预约生效",
          value: "2",
        },
      ],
      timeList: [
        { value: "01:00:00", text: "01:00:00" },
        { value: "02:00:00", text: "02:00:00" },
        { value: "03:00:00", text: "03:00:00" },
        { value: "04:00:00", text: "04:00:00" },
        { value: "05:00:00", text: "05:00:00" },
        { value: "06:00:00", text: "06:00:00" },
        { value: "07:00:00", text: "07:00:00" },
        { value: "08:00:00", text: "08:00:00" },
        { value: "09:00:00", text: "09:00:00" },
        { value: "10:00:00", text: "10:00:00" },
        { value: "11:00:00", text: "11:00:00" },
        { value: "12:00:00", text: "12:00:00" },
        { value: "13:00:00", text: "13:00:00" },
        { value: "14:00:00", text: "14:00:00" },
        { value: "15:00:00", text: "15:00:00" },
        { value: "16:00:00", text: "16:00:00" },
        { value: "17:00:00", text: "17:00:00" },
        { value: "18:00:00", text: "18:00:00" },
        { value: "19:00:00", text: "19:00:00" },
        { value: "20:00:00", text: "20:00:00" },
        { value: "21:00:00", text: "21:00:00" },
        { value: "22:00:00", text: "22:00:00" },
        { value: "23:00:00", text: "23:00:00" },
        { value: "24:00:00", text: "24:00:00" },
      ],
      effectdateInfo: {
        effect_date: "",
        effect_time: "",
        isYuYue: false, // 是否预约生效
      },
      oilPriceForm: {
        effectDate: this.formatter(new Date(), "yyyy-MM-dd hh:mm:ss"),
        pushDate: "",
        stationId: "",
        stationOillGunPriceList: [],
      },
      formRules: {
        stationId: {
          rules: [
            {
              required: true,
              errorMessage: "油站不能为空",
            },
          ],
        },
        effectDate: {
          rules: [
            {
              required: true,
              errorMessage: "生效时间不能为空",
            },
          ],
        },
      },
      value: 999,
      stationList: [],
      hobbys: [
        {
          text: "立即生效",
          value: true,
        },
      ],
      effectDateCheckboxVal: [],
      pushDateCheckboxVal: [],
      isDisabled: false, // 是否禁用确认按钮
    };
  },
  onShow() {
    this.init();
  },
  methods: {
    // 切换生效日期按钮
    handleChangeRadia(e) {
      let type = e.target.value;
      this.effectdateInfo.isYuYue = type === "2" ? true : false;
      if (type === "1") {
        // 立即生效
        this.oilPriceForm.effectDate = this.formatter(new Date(), "yyyy-MM-dd hh:mm:ss");
        this.effectdateInfo.effect_date = "";
        this.effectdateInfo.effect_time = "";
      } else {
        // 预约生效
        this.oilPriceForm.effectDate = "";
      }
    },
    // 选择生效时间--日期
    changeDate(val) {
      console.log(111, val);
      this.oilPriceForm.effectDate = val + " " + this.effectdateInfo.effect_time;
    },
    // 选择生效时间---时
    changeTime(val) {
      console.log(22, val);
      this.oilPriceForm.effectDate = this.effectdateInfo.effect_date + " " + val;
    },

    // 确认输入框的金额值，以及失去焦点时的事件
    priceConfirm(index, item) {
      console.log("确认价格：", index, item);
      console.log(this.oilPriceForm.stationOillGunPriceList);

      const num = Number(item.oilStationPrice);
      const reg = /^\d+(\.\d{1,2})?$/; // 两位小数点
      if (!item.oilStationPrice) {
        this.isDisabled = true;
        return uni.showToast({
          title: "值不能为空",
          icon: "error",
        });
      }

      // 判断 .xxx格式的数据 如 .23
      if (item.oilStationPrice.startsWith(".")) {
        uni.showToast({
          title: "请输入有效数值",
          icon: "error",
        });
        return (this.isDisabled = true);
      }

      if (Number.isNaN(num)) {
        uni.showToast({
          title: "请输入有效数值",
          icon: "error",
        });
        return (this.isDisabled = true);
      }

      if (num <= 0) {
        this.isDisabled = true;
        return uni.showToast({
          title: "不能小于等于0",
          icon: "error",
        });
      }
      if (!reg.test(num)) {
        this.isDisabled = true;
        return uni.showToast({
          title: "最多两位小数点",
          icon: "error",
        });
      }

      // 所有输入框回复原样
      this.oilPriceForm.stationOillGunPriceList.forEach((item) => (item.isEdit = false));
      this.isDisabled = false;
    },

    // 点击输入框聚焦，让对应输入框聚焦
    showInput(index, item) {
      this.oilPriceForm.stationOillGunPriceList[index].isEdit = true;
    },

    // 生效时间按钮 --- 旧版
    hanleImmediatelyStartDate(e) {
      if (e.detail.value.length && e.detail.value[0]) {
        this.oilPriceForm.effectDate = this.formatter(new Date(), "yyyy-MM-dd hh:mm:ss");
      } else {
        this.oilPriceForm.effectDate = "";
      }
    },

    // 推送时间
    hanleImmediatelyPushDate(e) {
      if (e.detail.value.length && e.detail.value[0]) {
        this.oilPriceForm.pushDate = this.formatter(new Date(), "yyyy-MM-dd hh:mm:ss");
      } else {
        this.oilPriceForm.pushDate = "";
      }
    },
    formatter(thistime, fmt) {
      let $this = new Date(thistime);
      let o = {
        "M+": $this.getMonth() + 1,
        "d+": $this.getDate(),
        "h+": $this.getHours(),
        "m+": $this.getMinutes(),
        "s+": $this.getSeconds(),
        "q+": Math.floor(($this.getMonth() + 3) / 3),
        S: $this.getMilliseconds(),
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ($this.getFullYear() + "").substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
      }
      return fmt;
    },
    goBack() {
      uni.navigateBack();
    },

    // 确认
    updateOilGunPrice() {
      this.$refs.baseForm
        .validate()
        .then((res) => {
          smallProgramUpdateOilGunPrice(this.oilPriceForm).then((res) => {
            if (res.code === 200) {
              this.pushDateCheckboxVal = [];
              this.effectDateCheckboxVal = [];
              this.oilPriceForm.effectDate = "";
              this.oilPriceForm.pushDate = "";
              this.effectdateInfo.effect_date = ""; // 生效时间设置
              this.effectdateInfo.effect_time = "";
              uni.showToast({
                title: "调价成功",
                duration: 1000,
              });
            } else {
              uni.showToast({
                title: res.msg,
                duration: 1000,
              });
            }
          });
        })
        .catch((err) => {});
    },

    // 选择油站
    stationChange(val) {
      this.oilPriceForm.stationId = val;
      getListByEnterpriseOrStationId({
        stationId: this.oilPriceForm.stationId,
      }).then((res) => {
        if (res.code === 200 && res.data && res.data.length) {
          res.data.forEach((item) => {
            item.isEdit = false;
          });
          this.oilPriceForm.stationOillGunPriceList = res.data;
          this.oilPriceForm.stationOillGunPriceList = this.oilPriceKey(this.oilPriceForm.stationOillGunPriceList, "oilStationPrice");
        } else {
          this.oilPriceForm.stationOillGunPriceList = [];
        }
      });
    },

    oilPriceKey(list, newKey) {
      let newObj = {};
      let arr = [];
      list.forEach((obj) => {
        newObj = Object.keys(obj).reduce((acc, key) => {
          if (key === "oilPrice") {
            acc[newKey] = obj[key];
          } else {
            acc[key] = obj[key];
          }
          return acc;
        }, {});
        arr.push(newObj);
      });
      return arr;
    },

    init() {
      getStationInfo().then((res) => {
        console.log(res.data, "res.data");
        if (res.code === 200) {
          if (res.data && res.data.length) {
            res.data.forEach((item) => {
              (item.text = item.stationName), (item.value = item.stationId);
            });
          }
          this.stationList = res.data;
          this.stationChange(this.stationList[0].value);
        } else {
          this.stationList = [];
        }
      });
    },
  },
};
</script>

<style lang="scss">
.con-oil-price-wraper {
  min-height: 100vh;
  background-color: #f5f5f9;
  padding: 40rpx;

  .info {
    .title_line {
      position: relative;
      margin-bottom: 30rpx;
      font-size: 24px;
    }

    // .title_line::after {
    //   content: "";
    //   display: block;
    //   position: absolute;
    //   height: 30px;
    //   width: 8px;
    //   left: -10px;
    //   top: 0;
    //   background-color: rgba(242, 131, 0, 1);
    // }
  }

  .operate {
    display: flex;
    justify-content: center;
    margin-top: 40rpx;

    .operate-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 0 20upx;
      width: 400upx;
    }
  }
}
</style>
